package main

import (
	"common/erpc"
	"context"
	"fmt"
	"io"
	"io/fs"
	"net"
	"os"
	"time"
)

func upload() error {
	ctx := context.Background()
	ctx, _ = context.WithTimeout(ctx, time.Second*30)
	c, err := net.Dial("tcp", "127.0.0.1:18082")

	if err != nil {
		return err
	}
	client := erpc.NewDRPCPiecestoreClient(c)
	//修改
	stream, err := client.Upload(ctx, "dfsdff",10,10)
	if err != nil {
		return err
	}
	file := "/Users/ljg/Desktop/estore.zip"
	f, err := os.Open(file)
	if err != nil {
		fmt.Println(err)
		return err
	}
	offset := 0
	buf := make([]byte, 1024)
	for {
		n, readErr := f.Read(buf)
		fmt.Println(n, readErr)
		var done = 0
		if readErr == io.EOF {
			fmt.Println("done = 1")
			done = 1
		}
		if sendErr := stream.Send(&erpc.Chunk{
			Offset: offset,
			Data:   buf[:n],
			Done:   done,
		}); sendErr != nil {
			return sendErr
		}
		fmt.Println(n, offset)

		offset += n
		if readErr != nil {
			fmt.Println(readErr)
			break
		}
		//if ctx.Err() != nil {
		//	fmt.Println("context err", ctx.Err())
		//	break
		//}
	}
	rs, err := stream.CloseAndRecv()
	if err != nil {
		fmt.Println(nil)
		return err
	}
	fmt.Println(rs.Hash)
	return nil
}
func download() error {
	ctx := context.Background()
	ctx, _ = context.WithTimeout(ctx, time.Second*30)
	c, err := net.Dial("tcp", "127.0.0.1:18082")
	if err != nil {
		return err
	}
	client := erpc.NewDRPCPiecestoreClient(c)
	defer client.Close()
	//修改
	stream, err := client.Download(ctx, "abcdefg",10)
	if err != nil {
		return err
	}
	file := "/Users/ljg/Desktop/estore_download.zip"
	f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE, fs.ModePerm)
	if err != nil {
		return err
	}
	defer f.Close()
	for {
		msg, readErr := stream.Recv()
		if readErr != nil {
			fmt.Println("end", readErr)
			break
		}

		//fmt.Println(msg.Offset)
		f.Write(msg.Data)
		if msg.Done == 1 {
			fmt.Println("done == 1")
			break
		}
	}
	stream.CloseAndRecv()
	return nil
}
func main() {
	fmt.Println(download())
	//fmt.Println(upload())
}
